/* eslint-disable no-lonely-if */
/* eslint-disable arrow-parens */
/* eslint-disable array-callback-return */
/* eslint-disable no-param-reassign */
/* eslint-disable react/sort-comp */
import ProLayout, { DefaultFooter } from '@ant-design/pro-layout';
import React, { useEffect } from 'react';
import Link from 'umi/link';
import router from 'umi/router';
import { Route } from 'dva/router';
import _ from 'loadsh';

import { connect } from 'dva';
import { Icon, Result, Button, Tabs } from 'antd';
import Authorized from '@/utils/Authorized';
import RightContent from '@/components/GlobalHeader/RightContent';
import { isAntDesignPro, getAuthorityFromRouter } from '@/utils/utils';
import { reloadAuthorized } from '@/utils/Authorized';
import logo from '../assets/logo.svg';
import styles from './BasicLayout.less'


const { TabPane } = Tabs;

const noMatch = (
  <Result
    status="403"
    title="403"
    subTitle="Sorry, you are not authorized to access this page."
    extra={
      <Button type="primary">
        <Link to="/user/login">Go Login</Link>
      </Button>
    }
  />
);

/**
 * use Authorized check all menu item
 * 将树形菜单平铺为一维数组后验证权限（本项目用不到authority:'admin'、'user'、'guest'）
 */
const menuDataRender = menuList => {
  return menuList.map(item => {
    const localItem = { ...item, children: item.children ? menuDataRender(item.children) : [] };
    return Authorized.check(item.authority, localItem, null);
  });
}


const defaultFooterDom = (
  <DefaultFooter
    copyright="2019 蚂蚁金服体验技术部出品"
    links={[
      {
        key: '加入QQ群',
        title: '加入QQ群',
        href: 'https://jq.qq.com/?_wv=1027&k=5baIhh4',
        blankTarget: true,
      },
      {
        key: 'github',
        title: <Icon type="github" />,
        href: 'https://gitee.com/sunpanyu',
        blankTarget: true,
      },
      {
        key: 'Ant Design pro 入门文档',
        title: 'Ant Design pro 入门文档',
        href: 'https://www.yuque.com/yuxuanbeishui/zog1rm',
        blankTarget: true,
      },
    ]}
  />
);

const footerRender = () => {
  if (!isAntDesignPro()) {
    return defaultFooterDom;
  }

  return (
    <>
      {defaultFooterDom}
      <div
        style={{
          padding: '0px 24px 24px',
          textAlign: 'center',
        }}
      >
        <a href="https://www.netlify.com" target="_blank" rel="noopener noreferrer">
          <img
            src="https://www.netlify.com/img/global/badges/netlify-color-bg.svg"
            width="82px"
            alt="netlify logo"
          />
        </a>
      </div>
    </>
  );
};

@connect(({ global, settings }) => ({
  collapsed: global.collapsed,
  settings,
}))
class BasicLayout extends React.Component {
  constructor(props) {
    super(props);
    const { routes } = props.route;
    const routeKey = '/tree/searchTree'; // routeKey 为设置首页设置 试试 '/dashboard/analysis' 或其他key值
    const allMenuData = this.updateTree(routes);
    const tabList = [];
    const allTabListKey = [];
    let homeInfo;  // 首页
    allMenuData.forEach((item) => {
      if (item.key === routeKey) {
        if (tabList.length === 0) {
          tabList.push(item);
        }
      }
      if (item.key) allTabListKey.push(item.key);
      if (item.key === routeKey) homeInfo = { ...item };
    });
    this.state = ({
      tabList, // 已经展示的tag列表
      tabListKey: [routeKey], // 已经展示的tag列表路由keys
      activeKey: routeKey, // 当前激活的路由key
      routeKey, // 默认页面的路由key
      allTabListKey, // 所有可用菜单路由key
      allMenuData, // 所有可跳转菜单
      homeInfo,  // 首页
    })
  }


  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'user/fetchCurrent',
    });
    dispatch({
      type: 'settings/getSetting',
    });

    // 解决退出之后权限菜单没有随角色改变而改变的问题
    reloadAuthorized();
  }

  UNSAFE_componentWillReceiveProps(props) {
    this.handleAddTabs(props);
  }

  updateTree = data => {
    const treeData = data;
    const treeList = [];
    // 递归获取树列表
    const getTreeList = dataArr => {
      dataArr.forEach(node => {
        if (!node.routes) {
          treeList.push({
            tab: node.name,
            key: node.path,
            closable: true,
            content: node.component,
          });
        }
        if (node.routes && node.routes.length > 0) {
          getTreeList(node.routes);
        }
      });
    };
    getTreeList(treeData);
    return treeList;
  };

  handleAddTabs = (props) => {
    // 用户点击菜单后,可以得到其路径地址
    const { location: { pathname, search } } = props || this.props;
    const { tabList, tabListKey, allTabListKey, allMenuData } = this.state;

    // if (allTabListKey.includes(pathname)) {
    //   if (!search) {
    //     router.push(pathname);
    //   } else {
    //     router.push({ pathname, search });
    //   }
    // } else {
    //   key = '/404';
    //   router.push('/404');
    // }

    allMenuData.forEach((item) => {
      if (item.key === pathname && pathname !== '/') {
        this.setState({
          tabList: _.uniq([...tabList, item]),
          tabListKey: _.uniq([...tabListKey, item.key]),
          activeKey: pathname,
        });
      } else {
        if (!allTabListKey.includes(pathname)) {
          router.push('/404');
        }
      }
    });
  }

  // get children authority
  handleMenuCollapse = payload => {
    const { dispatch } = this.props;
    dispatch({
      type: 'global/changeLayoutCollapsed',
      payload,
    });
  };

  // 切换 tab页
  onChange = key => {
    this.setState({ activeKey: key });
    router.push(key)
  };

  // 新增或删除tabs触发函数
  onEdit = (targetKey, action) => {
    this[action](targetKey);
  }

  remove = (targetKey) => {
    const { activeKey, tabList } = this.state;
    const tabListArr = [];
    const tabListKey = [];
    let lastIndex;
    tabList.forEach((item, index) => {
      if (item.key === targetKey) {
        lastIndex = index - 1;
      } else {
        tabListArr.push(item)
        tabListKey.push(item.key)
      }
    });
    // 如果删除的是激活的标签tab,则转移到其上一个tab上
    let newActiveKey;
    if (lastIndex >= 0 && activeKey === targetKey) {
      newActiveKey = tabList[lastIndex].key;
    } else if (lastIndex < 0 && activeKey === targetKey) {
      newActiveKey = tabList.length > 1 ? tabList[lastIndex + 2].key : '';
    } else {
      newActiveKey = activeKey;
    }
    this.setState({ tabList: tabListArr, activeKey: newActiveKey, tabListKey }, () => {
      router.push(newActiveKey);
    });
  }

  render() {
    const { route: { routes }, settings, location, children } = this.props;
    const { pathname = '/' } = location;

    const { tabList, activeKey, homeInfo } = this.state;

    const authorized = getAuthorityFromRouter(routes, pathname) || {
      authority: undefined,
    };
    return (
      <ProLayout
        logo={logo}
        menuHeaderRender={(logoDom, titleDom) => (
          <Link to="/">
            {logoDom}
            {titleDom}
          </Link>
        )}
        onCollapse={this.handleMenuCollapse}
        menuItemRender={(menuItemProps, defaultDom) => {
          /**
           * 菜单遍历函数
           * @param menuItemProps -- 包含name、path、icon、compoent等
           * @param defaultDom -- 包含菜单的icon、name的dom元素
           */
          if (menuItemProps.isUrl || menuItemProps.children) {
            return defaultDom;
          }

          return <Link to={menuItemProps.path}>{defaultDom}</Link>;
        }}
        footerRender={footerRender}
        menuDataRender={menuDataRender}
        // menuProps={{
        //   onClick:(item)=>console.log(111),
        // }}
        rightContentRender={rightProps => <RightContent {...rightProps} />}
        {...this.props}
        {...settings}
      >
        {
          tabList && Array.isArray(tabList) && tabList.length > 0 ? (
            <Tabs
              className={[styles['override-ant-tabs-bar'], styles['override-ant-card-bordered']].join(' ')}
              activeKey={activeKey}
              onChange={this.onChange}
              // tabBarExtraContent={operations}
              // tabBarStyle={{ background: '#fff' }}
              // tabPosition="top"
              tabBarGutter={-1}
              hideAdd
              type="editable-card"
              onEdit={this.onEdit}
            >
              {
                tabList.map(item => (
                  <TabPane tab={item.tab} key={item.key}>
                    <Authorized authority={authorized.authority} noMatch={noMatch}>
                      <Route key={item.key} path={item.path} component={item.content} exact={item.exact} />
                    </Authorized>
                  </TabPane>
                ))
              }
            </Tabs>)
            : <Route key={homeInfo.key} path={homeInfo.path} component={homeInfo.content} exact={homeInfo.exact} />
        }
      </ProLayout>
    )
  }
}


export default BasicLayout;